package com.yykj.drup.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yykj.common.vo.ResultVO;
import com.yykj.drup.server.dto.ChooseStoreProductsDto;
import com.yykj.drup.server.dto.NeedProductsDto;
import com.yykj.drup.server.form.WestDrug;
import com.yykj.drup.server.model.DoctorStore;
import com.yykj.drup.server.model.Product;
import com.yykj.drup.server.model.Store;
import com.yykj.drup.server.param.ChooseStoreParam;
import com.yykj.drup.server.service.DoctorStoreService;
import com.yykj.drup.server.service.ProductService;
import com.yykj.drup.server.service.StoreService;
import com.yykj.drup.server.service.feign.MessageCenterServerFeign;
import com.yykj.drup.server.service.feign.PrescriptionServerFeign;
import com.yykj.prescription.client.dto.PrescriptionDetailDTO;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author zeng
 * @Date 2022/3/9
 */
@RestController
@Api(tags = "药品门店")
@RequestMapping("/api/drug")
@AllArgsConstructor
public class StoreController {

    final StoreService storeService;
    final DoctorStoreService doctorStoreService;
    final ProductService productService;
    final MessageCenterServerFeign messageCenterServerFeign;
    final PrescriptionServerFeign prescriptionServerFeign;

    @ApiOperation("添加医生常用药店")
    @GetMapping("/store/addOftenDoctor")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "doctorId",value = "医生主键ID",required = true)
    })
    public ResultVO<Store> addOftenDoctor(
            @RequestParam(name = "doctorId") String doctorId,Integer[] ids){
            return ResultVO.success(doctorStoreService.insertDoctor(doctorId, ids));
    }

    @ApiOperation("删除医生常用药店")
    @GetMapping("/store/delOftenDoctor")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "doctorId",value = "医生主键ID",required = true),
            @ApiImplicitParam(name = "storeId",value = "药店列表的主键ID",required = true)
    })
    public ResultVO findOftenDoctor(
            @RequestParam(name = "doctorId") String doctorId,
            @RequestParam(name = "storeId") Integer storeId
    ){
        Integer i = doctorStoreService.doctorRemoveStore(doctorId,storeId);
        if (i != 0){
            return ResultVO.success(i);
        }
       return ResultVO.error("操作失败");
    }

    @ApiOperation("搜索药店列表")
    @GetMapping("/store/findDoctors")
    @ApiImplicitParam(name = "shopName",value = "药店名称")
    @ApiResponses({
            @ApiResponse(code = 0,message = "",response =Store.class )
    })
    public ResultVO findDoctors(
            @RequestParam(name = "doctorId") String doctorId,
            @RequestParam(name = "shopName",required = false) String shopName
    ){
        QueryWrapper<Store> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(shopName),"shop_name",shopName).eq("is_deleted",0).orderByAsc("id");
        List<Store> stores = storeService.list(wrapper);
        List<Integer> storeIds = storeService.findByDoctorId(doctorId).stream().map(Store::getId).collect(Collectors.toList());
        if (!stores.isEmpty() && !storeIds.isEmpty()){
            stores.forEach(s ->{
                boolean contains = storeIds.contains(s.getId());
                s.setDoctorIsExist(contains);
            });
        }
        return ResultVO.success(stores);
    }

    @ApiOperation("查询医生常用药店")
    @GetMapping("/store/findOftenDoctor")
    @ApiResponses({
            @ApiResponse(code = 0,message = "",response =Store.class )
    })
    @ApiImplicitParam(name = "doctorId",value = "医生标识",required = true)
    public ResultVO findOftenDoctor(@RequestParam(name = "doctorId") String doctorId){
        List<Store> stores = storeService.findByDoctorId(doctorId);
        return ResultVO.success(stores);
    }

    @ApiOperation("设置医生常用药店序列")
    @GetMapping("/stort/stortOftenDoctor")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "doctorId",value = "医生主键ID",required = true)
    })
    @Transactional
    public ResultVO stortOftenDoctor(@RequestParam(name = "doctorId") String doctorId,Integer[] ids){

        for (int i = 0; i < ids.length; i++) {
            QueryWrapper<DoctorStore> wrapper = new QueryWrapper();
            wrapper.eq("doctor_id",doctorId).eq("store_id",ids[i]);
            DoctorStore doctorStore = new DoctorStore();
            doctorStore.setSort(i);
            boolean b = doctorStoreService.update(doctorStore, wrapper);
            if(!b){
                return ResultVO.error("设置失败");
            }
        }
        return ResultVO.success();
    }

    @ApiOperation("获取自选药店列表及含有药品情况")
    @PostMapping("/stort/chooseStore")
    @ApiResponses({
            @ApiResponse(code = 0,message = "",response =ChooseStoreProductsDto.class )
    })
    public ResultVO chooseStore(@RequestBody ChooseStoreParam param){
        Map<String,Object> resultMap = new HashMap<>();
        List<ChooseStoreProductsDto> chooseStoreProductsDtos = new ArrayList<>();
        //feign调取prescription-server，根据处方标识获取处方中药品集合 X00120220317000003
        ResultVO<PrescriptionDetailDTO> prescriptionDetailDTOResultVO = prescriptionServerFeign.prescriptionInfo(param.getPrescriptionId());
        if (prescriptionDetailDTOResultVO.getCode() != 0){
            return prescriptionDetailDTOResultVO;
        }
        PrescriptionDetailDTO detailDTO = prescriptionDetailDTOResultVO.getData();

        //获取医生ID
        String doctorId = detailDTO.getDoctorId();
        //获取处方药品列表
        //获取整理药方药品数据
        List<WestDrug> westDrugList = productService.findWestDrugs(detailDTO);
        //List<PrescriptionDrugWestDTO> westDrugList = detailDTO.getWestDrugList();
        //转换处方需要的药品列表（方便前端处理）
        List<NeedProductsDto> needProductsDto = westDrugList.stream().map(l -> new NeedProductsDto(l.getDrugId(),l.getDrugName(),l.getCnt())).collect(Collectors.toList());
        //获取处方需要的药品的id列表，方便后续处理
        List<Integer> drugIds = westDrugList.stream().map(WestDrug :: getDrugId).collect(Collectors.toList());
        //获取药店列表（医生设置的常用药店排在前面）
        List<Store> stores = storeService.findStoreList(doctorId,param.getStoreName());
        //遍历药店获取药店对于处方药品缺失的药品信息
        for (Store store : stores) {
            ChooseStoreProductsDto chooseStoreProductsDto = new ChooseStoreProductsDto();
            chooseStoreProductsDto.setStore(store);
            //List<Integer> drugIds = drugs.stream().map(Integer::parseInt).collect(Collectors.toList());
            List<Product> storeMissingProduct = productService.findStoreMissingProduct(store.getId(), drugIds);
            chooseStoreProductsDto.setProducts(storeMissingProduct);
            chooseStoreProductsDtos.add(chooseStoreProductsDto);
        }
        resultMap.put("needProducts",needProductsDto);
        resultMap.put("chooseStoreProducts",chooseStoreProductsDtos);
        return ResultVO.success(resultMap);
    }

}
